package com.xiaolanshu.controller;

import com.xiaolanshu.entity.Praise;
import com.xiaolanshu.interceptor.UserHolder;
import com.xiaolanshu.service.PraiseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/praise")
public class PraiseController {

    @Autowired
    private PraiseService praiseService;

    @PostMapping("/{noteId}")
    public ResponseEntity praise(@PathVariable Long noteId){
        //从线程当中获取用户id（拦截器从请求头获取了用户信息并缓存到线程当中）
        Long userId = UserHolder.getUserId();

        //根据用户id和笔记id查找点赞信息
        Praise praise = praiseService.findPraise(userId,noteId);

        //如果表中不存在点赞信息则添加记录
        if (praise == null){
            Praise praiseNew = new Praise();
            praiseNew.setUserId(userId);
            praiseNew.setNoteId(noteId);
            praiseNew.setPraise(1);
            praiseService.savePraise(praiseNew);
        }
        //点赞信息存在，1为点赞，0为取消点赞
        else {
            //收到请求时，如果praise为1，则修改表的数据为0
            if(praise.getPraise()==1){
                praise.setPraise(0);
                praiseService.updateById(praise);
                return ResponseEntity.ok("取消点赞");
            }
            //收到请求时，如果praise为0，则修改表的数据为1
            else
                praise.setPraise(1);
                praiseService.updateById(praise);
        }

        return ResponseEntity.status(200).body("点赞成功");
    }

}
